// 住院发药
import React from 'react';
import { Card, Row, Col, DatePicker, Button, Select, Checkbox, Tabs, Table, Input, Divider, message, Modal, Tooltip } from 'antd';
import { $loopPrint } from '../lodop/Common/Print';
import store from 'store';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import './style/index.less';
import ProtogenesisTable from './component/ProtogenesisTable';
import RejectDispensingCause from './component/RejectDispensingCause';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import PublicModalTable from './../common/PublicModalTable';

let timeout;
let { Option } = Select;
const { TabPane } = Tabs;
export default class HPDispensing extends React.Component {
    constructor() {
        super();
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        this.state = {
            pharmacy: userData.locID, // 药房
            startDate: Moment(), // 开始日期
            endDate: Moment(), // 结束日期
            selectData: {}, // 下拉框数据
            offsetDrug: false, // 冲减退药
            depDispensing: false, // 科室发药
            basicHeight: 0, // 查询款高度
            wardSelectedRows: [], // 选中的行数据
            wardSelectedRowKeys: [], // 病区选中行数key值
            wardRowId: "", // 病区选中行id
            activeTabPaneKey: '1',
            wardSelectData: [], // 病区下拉框数据
            columns: [], // 左侧表头
            tableData: [], // 左侧列表数据
            patNo: undefined, // 登记号
            registrationColumns: [], // 登记号表头
            registrationTableData: [], // 登记号列表数据
            activeDispensingTab: '1', // 发药汇总、明细
            summarizingColumns: [], // 发药汇总表头数据
            summarizingTableData: [], // 发药汇总列表数据
            dispCatData: [], // 发药类别
            dispDetailColumns: [], // 发药明细表头数据
            dispDetailTableData: [], // 发药明细列表数据
            summarizingCheckbox: [], // 发要汇总选中行数据
            dispDetailCheckbox: [], // 发要明细选中行数据
            priorityCheckboxData: [], // 医嘱优先级数据
            registrationRowId: "", // 登记号选中行id
            registrationRowData: {},
            detailWidthTotal: '',
            columnsCollect: [], //汇总表头数据
            modalColumns: [], //详情表头数据
            listLength: '',
            parameterCode: '',
            modalData: [],
            drugName: undefined,
            reasonSelectData: [], // 拒绝发药原因
        };
        this.modalColumns = [
            {
                key: 1,
                title: '库存项代码',
                dataIndex: 'stockCode',
                align: "center",
                width: '22%'
            },
            {
                key: 2,
                title: '库存项描述',
                dataIndex: 'stockDesc',
                align: "center",
                width: '24%',
            },
            {
                key: 5,
                title: '库存分类',
                dataIndex: 'stkSubCatDesc',
                align: "center",
                width: '16%',
            },
            {
                key: 3,
                title: '包装规格',
                dataIndex: 'stockSpec',
                align: "center",
                width: '12%',
            },
            {
                key: 6,
                title: '基本单位',
                dataIndex: 'baseUnitDesc',
                align: "center",
                width: '12%',
            },
            {
                key: 7,
                title: '入库单位',
                dataIndex: 'purUnitDesc',
                align: "center",
            }
        ]
    }

    componentDidMount() {
        this.getColumns();
        this.getSummarizingColumns();
        this.getSelectData();
        this.getDetailTableColumns();
        this.getDetailListTableColumns();
        this.setState({ basicHeight: document.getElementById("dep-ward-dispensing").clientHeight })
    }

    componentWillUnmount() {
        // 组件销毁前将静止让setState修改state的状态
        this.setState = (state, callback) => { return; }
    }
    // 获取明系列表头数据
    getDetailTableColumns1 = () => {
        let { userInfo } = this.state;
        let data = {
            params: [{
                reactCode: ['DepartmentDrugInformationMaint'],
                compontName: 'DepartmentDrugInformationMaint',
                type: 'C',
            }]
        }
        $http.post('urlS', this, {
            code: '01040073',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let arr = res.result.C && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                        return {
                            ...item,
                            key: index + 1,
                            title: <div onDoubleClick={() => { this.columnRef.onOpenModel(); }}>{userInfo.language == 'EN' ? item.enDescripts : item.title}</div>,
                            render: (text, record) => {
                                if (item.code == 'maxQty') {
                                    return (<Input min={0} style={{ width: '80%' }} type="number" value={text} onChange={(e) => this.handleFieldChange(e, 'maxQty', record.stkLocID)} />)
                                } else if (item.code == 'minQty') {
                                    return (<Input min={0} style={{ width: '80%' }} type="number" value={text} onChange={(e) => this.handleFieldChange(e, 'minQty', record.stkLocID)} />)
                                } else if (item.code == 'repLevQty') {
                                    return (<Input min={0} style={{ width: '80%' }} type="number" value={text} onChange={(e) => this.handleFieldChange(e, 'repLevQty', record.stkLocID)} />)
                                } else if (item.code == 'stockBin') {
                                    return (<Select mode="multiple" style={{ width: '100%' }} value={text} onChange={(e) => this.handleFieldSelect(e, 'stockBin', record.stkLocID)}>
                                        {this.state.SelectCode.length > 0 && this.state.SelectCode.map((item, i) => {
                                            return <Option value={item.stkBinID + ''} key={i}>{item.stkBinDesc}</Option>
                                        })}
                                    </Select>
                                    )
                                } else {
                                    return text;
                                }
                                // return (<span className={record.warnID == 1 && item.code == 'warnStatus' ? 'redColor' : record.warnID == 2 && item.code == 'warnStatus' ? 'cyanColor': ''}>{text}</span>)
                            }
                        }
                    }) : '';
                    let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                    this.setState({ columns: filterArr, detailWidthTotal: res.totalWidth, ChineseEnglishSize: userInfo.language == 'EN' ? res.result.language.EN : res.result.language.CN })
                }
            }
        });
    };
    // 获取汇总列表头数据
    getDetailTableColumns = () => {
        let data = {
            params: [{
                compontName: 'HPDispensingCollect',
                type: 'C',
            }]
        }
        $http.post('urlS', this, {
            code: '01040073',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let arr = res.result.C && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                        return {
                            ...item,
                            key: index + 1,
                            title: <div onDoubleClick={() => {
                                this.setState({ parameterCode: 'HPDispensingCollect' }, () => {
                                    this.columnRef.onOpenModel();
                                })
                            }}>{item.title}</div>
                        }
                    }) : '';
                    // console.log(arr)
                    let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                    this.setState({ columnsCollect: filterArr, detailWidthTotal: res.totalWidth })
                }
            }
        })
    };

    // 获取明系列表头数据
    getDetailListTableColumns = () => {
        let data = {
            params: [{
                compontName: 'HPDispensingDetail',
                type: 'C',
            }]
        }
        $http.post('urlS', this, {
            code: '01040073',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let arr = res.result.C && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
                        return {
                            ...item,
                            key: index + 1,
                            title: <div onDoubleClick={() => {
                                this.setState({ parameterCode: 'HPDispensingDetail' }, () => {
                                    this.columnRef.onOpenModel();
                                })
                            }}>{item.title}</div>,
                        }
                    }) : '';
                    let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                    this.setState({ modalColumns: filterArr, listLength: res.totalWidth });
                }
            }
        })
    };

    // 取发药下拉框数据集
    getSelectData = () => {
        let data = {
            params: []
        }
        $http.post('urlS', this, {
            code: "02040021",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let dispCatData = res.dispCat && res.dispCat.length > 0 ? res.dispCat.map((item) => {
                        return {
                            ...item,
                            checked: false,
                            disabled: true
                        }
                    }) : [];
                    let priorityCheckboxData = res.priority && res.priority.length > 0 ? res.priority.map((item) => {
                        return {
                            ...item,
                            checked: false,
                        }
                    }) : [];
                    let reasonSelectData = res.reason ? res.reason : [];
                    this.setState({
                        selectData: res,
                        dispCatData,
                        offsetDrug: res.locParam && res.locParam.ResFlag ? res.locParam.ResFlag : false,
                        priorityCheckboxData,
                        reasonSelectData,
                        startDate: res.defaultStartDate ? Moment(res.defaultStartDate) : Moment(),
                        endDate: res.defaultEndDate ? Moment(res.defaultEndDate) : Moment()
                    }, () => {
                        this.getTableData();
                    })
                }
            }
        })
    }

    onRef = ref => {
        this.child = ref;
    }

    // 药房查询条件
    handlePharmacyOnChange = e => {
        this.setState({ pharmacy: e })
    }

    // 开始日期
    handleStartDate = e => {
        this.setState({ startDate: e })
    }

    // 结束日期
    handleEndDate = e => {
        this.setState({ endDate: e })
    }

    // 冲减退药
    handleCheckbox = e => {
        this.setState({ offsetDrug: e.target.checked })
    }

    // 科室发药
    handleDepartmentCheckbox = e => {
        this.setState({
            depDispensing: e.target.checked,
            activeTabPaneKey: '1', // 重置左侧列表tab默认值
            activeDispensingTab: '1',
        }, () => {
            this.getTableData(); // 重新查询左侧列表数据
        })
    }

    // 切换医嘱查询页签
    toggleTabPane = key => {
        this.resetDetailData();
        this.setState({
            wardSelectedRowKeys: [],
            wardSelectedRows: [],
            wardRowId: '',
            registrationRowId: "",
            registrationRowData: {},
        }, () => {
            this.setState({ activeTabPaneKey: key }, () => {
                if (this.state.activeTabPaneKey === '2') {
                    if (!(this.state.registrationColumns && this.state.registrationColumns.length > 0)) {
                        this.getRegistrationColumns(); // 获取登记号表头数据
                    }
                }
            })
        })
    }

    // 获取病区表头数据
    getColumns = () => {
        let data = [
            {
                title: '病区',
                dataIndex: 'wardDesc',
                width: '150px',
                align: "center",
            }
        ]
        this.setState({ columns: data })
    }

    // 重置明细数据
    resetDetailData = () => {
        let dispCatData = JSON.parse(JSON.stringify(this.state.dispCatData));
        let priorityCheckboxData = JSON.parse(JSON.stringify(this.state.priorityCheckboxData));
        for (var i = 0; i < dispCatData.length; i++) {
            dispCatData[i].checked = false;
            dispCatData[i].disabled = true;
        }
        for (var i = 0; i < priorityCheckboxData.length; i++) {
            priorityCheckboxData[i].checked = false;
        }
        this.setState({
            summarizingTableData: [],
            dispDetailTableData: [],
            summarizingCheckbox: [], // 发要汇总选中行数据
            dispDetailCheckbox: [], // 发要明细选中行数据
            dispCatData,
            priorityCheckboxData
        })
    }

    // 获取病区列表数据
    getWardTableData = () => {
        let { pharmacy, startDate, endDate, depDispensing } = this.state;
        let data = {
            params: [{
                startDate: startDate ? Moment(startDate).format('YYYY-MM-DD') : "", // 开始日期
                endDate: endDate ? Moment(endDate).format('YYYY-MM-DD') : "", // 截止日期
                recLocID: pharmacy, // 药房科室I
                locDispFlag: depDispensing, // 是否为科室发药
            }],
            pagination: [{
                pageSize: 10000,
                currentPage: 1
            }]
        }
        $http.post('urlS', this, {
            code: "02040022",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    for (var i = 0; i < res.rows.length; i++) {
                        res.rows[i].key = i
                    }
                    this.setState({
                        tableData: res.rows,
                        wardSelectedRowKeys: [],
                        wardSelectedRows: [],
                        wardRowId: '',
                    })
                }
            }
        })
    }

    // 获取左侧列表数据
    getTableData = () => {
        if (this.state.activeTabPaneKey === '1') {
            this.getWardTableData();
        } else {
            this.getRegistrationTableData();
        }
    }

    // 请求病区下拉框数据(病区)
    handleWardSelectData = (value) => {
        if (timeout) {
            clearTimeout(timeout);
            timeout = null;
        }
        timeout = setTimeout(() => {
            if (value) {
                let data = {
                    params: [{
                        alias: value
                    }]
                }
                $http.post('urlS', this, {
                    code: "02040003",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            this.setState({ wardSelectData: res.result })
                        }
                    }
                })
            }
        }, 300)
    }

    // 获取登记号表头
    getRegistrationColumns = () => {
        let data = [
            {
                title: '姓名',
                dataIndex: 'patName',
                width: '100px',
                align: 'center',
            },
            {
                title: '登记号',
                dataIndex: 'patNo',
                width: '80px',
                align: 'center'
            },
            {
                title: '诊断',
                dataIndex: 'diagStr',
                width: '200px',
                align: 'center',
                render: (text, record) => {
                    return (
                        <Tooltip title={text}>
                            <span className="ellipsis" style={{ width: '100%', display: 'block' }}>{text}</span>
                        </Tooltip>
                    )
                }
            }
        ]
        this.setState({ registrationColumns: data })
    }

    // 获取登记号列表数据
    getRegistrationTableData = () => {
        let { pharmacy, startDate, endDate, depDispensing, patNo } = this.state;
        let data = {
            params: [{
                startDate: startDate ? Moment(startDate).format('YYYY-MM-DD') : "", // 开始日期
                endDate: endDate ? Moment(endDate).format('YYYY-MM-DD') : "", // 截止日期
                recLocID: pharmacy, // 药房科室I
                locDispFlag: depDispensing, // 是否为科室发药
                patNameOrNo: patNo
            }],
            pagination: [{
                pageSize: 10000,
                currentPage: 1
            }]
        }
        $http.post('urlS', this, {
            code: "02040049",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    for (var i = 0; i < res.rows.length; i++) {
                        res.rows[i].key = i
                    }
                    this.setState({
                        registrationTableData: res.rows,
                        registrationRowId: "",
                        registrationRowData: {},
                    })
                }
            }
        })
    }
    //组件权限编辑器
    onColumnRef = (ref) => {
        this.columnRef = ref;
    };
    // 描述回车事件
    stockDescOnPressEnter = (e) => {
        let top = document.getElementById('stock-desc').getBoundingClientRect().top + 40 + 'px';
        let left = document.getElementById('stock-desc').getBoundingClientRect().left + 'px'; // 如果弹窗宽度修改了则要基于600做减法(比如变成了800则需要减去200)
        this.setState({
            top,
            left
        });
        this.getModalListData(e.target.value);
        this.child.showModal();
    };

    // 获取描述列表数据
    getModalListData(alias) {
        let data = {
            params: [
                {
                    stockAlias: alias, // 库存项描述别名
                    frLocID: this.state.frLocDr ? this.state.frLocDr : undefined
                }
            ]
        };
        $http.post('urlS', this, {
            code: "02020042",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    for (var i = 0; i < res.result.length; i++) {
                        res.result[i].key = i
                    }
                    this.setState({ modalData: res.result })
                } else {
                    this.setState({ modalData: [] })
                }
            }
        })
    }
    // 操作弹框
    onClickRowPublic = (record) => {
        return {
            onDoubleClick: () => {
                this.confirmSelection(record);
            }
        }
    };
    // 双击选中行数据的回调
    confirmSelection = (record) => {
        // this.resetFields();
        this.setState({ drugName: record.stockDesc }, () => {
            this.handleDispensingDetailData();
            // 关闭弹窗
            this.child.handleCancel();
        })
    };

    handleDrugNameChange = (e) => {
        this.setState({ drugName: e.target.value }, () => {
            if (!this.state.drugName) {
                this.handleDispensingDetailData()
            }
        });
    };
    // 病区
    handleWardOnChange = e => {
        this.setState({ wardID: e }, () => {
            let arr = JSON.parse(JSON.stringify(this.state.tableData));
            if (arr && arr.length > 0) {
                let tableData = arr.filter(function (item) { return item.wardID === e });
                this.setState({ tableData })
            }
        })
    }

    // 病区行操作
    handleWardOnRow = (record) => {
        return {
            onClick: () => {
                let { wardSelectedRowKeys, wardSelectedRows } = this.state;
                let findFlag = false;
                let start = 0;
                if (wardSelectedRowKeys) {
                    wardSelectedRowKeys.find(function (value, key) {
                        if (value === record.key) {
                            //遍历找到选中的数据，并记录下选中数据在数组中的key
                            findFlag = true;
                            start = key;
                        }
                    })
                }
                if (findFlag) {
                    //再次点击移除选中
                    wardSelectedRowKeys.splice(start, 1);
                    wardSelectedRows.splice(start, 1);
                } else {
                    //将点击的行添加到选中
                    wardSelectedRowKeys.push(record.key);
                    wardSelectedRows.push(record);
                }
                if (this.state.wardRowId === "") {
                    this.setState({
                        wardRowId: record.key,
                        wardSelectedRowKeys,
                        wardSelectedRows
                    });
                } else {
                    if (this.state.wardRowId !== record.key) {
                        this.setState({
                            wardRowId: record.key,
                            wardSelectedRowKeys,
                            wardSelectedRows
                        });
                    } else {
                        this.setState({
                            wardRowId: "",
                            wardSelectedRowKeys,
                            wardSelectedRows,
                        });
                    }
                }
            }
        }
    }

    handleWardRowClassName = (record) => {
        return (("^" + this.state.wardSelectedRowKeys.join("^") + "^").indexOf("^" + record.key + "^") > -1) ? 'clickRowStyle' : '';
    }

    handlePatNoOnChange = e => {
        this.setState({ patNo: e.target.value })
    }

    // 切发药汇总、明细tab
    toggleDispensingTabPane = key => {
        this.setState({ activeDispensingTab: key }, () => {
            if (this.state.activeTabPaneKey === '2') {
                if (this.state.activeDispensingTab === '1') {
                    this.getSummarizingTableData("registration"); // 发要汇总
                } else if (this.state.activeDispensingTab === '2') {
                    if (!(this.state.dispDetailColumns && this.state.dispDetailColumns.length > 0)) {
                        this.getDispDetailColumns();
                    }
                    this.getDispDetailTableData("registration");
                }
            } else {
                if (this.state.activeDispensingTab === '1') {
                    this.getSummarizingTableData(); // 发要汇总
                } else if (this.state.activeDispensingTab === '2') {
                    if (!(this.state.dispDetailColumns && this.state.dispDetailColumns.length > 0)) {
                        this.getDispDetailColumns();
                    }
                    this.getDispDetailTableData();
                }
            }
        })
    }

    // 查询发药明细数据
    handleDispensingDetailData = () => {
        let { dispCatData, wardSelectedRows } = this.state;
        let arr = JSON.parse(JSON.stringify(dispCatData));
        let wardData = JSON.parse(JSON.stringify(wardSelectedRows));
        let dispCat = [];
        for (var i = 0; i < wardData.length; i++) {
            dispCat = dispCat.concat(wardData[i].dispCat)
        }
        let filterArr = [];
        for (var i = 0; i < arr.length; i++) {
            let dispCatID = arr[i].dispCatID;
            let isExist = false;
            let obj = arr[i];
            arr[i].checked = false;
            arr[i].disabled = false;
            for (var j = 0; j < dispCat.length; j++) {
                if (dispCatID === dispCat[j]) {
                    isExist = true
                    break;
                }
            }
            if (isExist) {
                obj.checked = true
            } else {
                obj.disabled = true
            }
            filterArr.push(obj)
        }
        this.setState({ dispCatData: filterArr }, () => {
            if (this.state.activeDispensingTab === '1') {
                this.getSummarizingTableData(); // 发要汇总
            } else {
                this.getDispDetailTableData(); // 发药明细
            }
        })
    }

    // 获取发药汇总表头数据
    getSummarizingColumns = () => {
        let data = [
            {
                title: '药品名称',
                dataIndex: 'stockDesc',
                width: 300,
                align: "center",
            },

            {
                title: '数量',
                dataIndex: 'sum',
                width: 200,
                align: "center"
            },
            {
                title: '单位',
                dataIndex: 'unitDesc',
                width: 100,
                align: "center"
            },
            {
                title: '剂型',
                dataIndex: 'formDesc',
                width: 100,
                align: "center"
            },
            {
                title: '规格',
                dataIndex: 'stockSpec',
                width: 200,
                align: "center"
            },
            {
                title: '库存',
                dataIndex: 'qty',
                width: 100,
                align: "center"
            },
            {
                title: '生产厂家',
                dataIndex: 'manfDesc',
                align: "center"
            },
        ]
        this.setState({ summarizingColumns: data })
    }

    // 获取发要汇总列表数据
    getSummarizingTableData = (flag) => {
        let { pharmacy, startDate, endDate, wardSelectedRows, depDispensing, priorityCheckboxData, registrationRowData, drugName } = this.state;
        let wardData = JSON.parse(JSON.stringify(wardSelectedRows));
        let dispCatData = JSON.parse(JSON.stringify(this.state.dispCatData));
        let arr = [];
        let priority = [];
        for (var i = 0; i < dispCatData.length; i++) {
            if (dispCatData[i].checked) {
                arr.push(dispCatData[i].dispCatID)
            }
        }
        for (var i = 0; i < priorityCheckboxData.length; i++) {
            if (priorityCheckboxData[i].checked) {
                priority.push(priorityCheckboxData[i].id)
            }
        }
        for (var i = 0; i < wardData.length; i++) {
            wardData[i].dispCat = arr
        }
        let data = {
            params: [{
                startDate: startDate ? Moment(startDate).format('YYYY-MM-DD') : "", // 开始日期
                endDate: endDate ? Moment(endDate).format('YYYY-MM-DD') : "", // 截止日期
                recLocID: pharmacy, // 药房科室ID
                ward: flag === "registration" ? undefined : wardData, // 病区
                adm: flag === "registration" ? registrationRowData : undefined,
                priority, // 医嘱优先级
                locDispFlag: depDispensing, // 是否为科室发药
                stockDesc: drugName ? drugName : undefined
            }]
        }
        $http.post('urlS', this, {
            code: "02040023",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    for (var i = 0; i < res.rows.length; i++) {
                        res.rows[i].key = i
                        res.rows[i].check = true;
                        if (parseInt(res.rows[i].sum) > parseInt(res.rows[i].qty)) {
                            res.rows[i].rowClassName = "Y"
                        }
                    }
                    this.setState({ summarizingTableData: res.rows, summarizingCheckbox: res.rows })
                } else {
                    this.setState({ summarizingTableData: [] })
                }
            }
        })
    }

    // 修改checkbox
    changeCheckbox = (e, item) => {
        let dispCatData = JSON.parse(JSON.stringify(this.state.dispCatData));
        for (var i = 0; i < dispCatData.length; i++) {
            if (dispCatData[i].dispCatID === item.dispCatID) {
                dispCatData[i].checked = e.target.checked;
                break;
            }
        }
        this.setState({ dispCatData }, () => {
            if (this.state.activeDispensingTab === '1') {
                this.getSummarizingTableData(); // 发要汇总
            } else if (this.state.activeDispensingTab === '2') {
                this.getDispDetailTableData();
            }
        })
    }

    // 优先级
    priorityCheckboxChange = (e, item) => {
        let priorityCheckboxData = JSON.parse(JSON.stringify(this.state.priorityCheckboxData));
        for (var i = 0; i < priorityCheckboxData.length; i++) {
            if (priorityCheckboxData[i].id === item.id) {
                priorityCheckboxData[i].checked = e.target.checked;
                break;
            }
        }
        this.setState({ priorityCheckboxData }, () => {
            if (this.state.activeTabPaneKey === '2') {
                if (this.state.activeDispensingTab === '1') {
                    this.getSummarizingTableData("registration"); // 发要汇总
                } else if (this.state.activeDispensingTab === '2') {
                    this.getDispDetailTableData("registration");
                }
            } else {
                if (this.state.activeDispensingTab === '1') {
                    this.getSummarizingTableData(); // 发要汇总
                } else if (this.state.activeDispensingTab === '2') {
                    this.getDispDetailTableData();
                }
            }
        })
    }

    // 获取发药明细tabs栏表头数据
    getDispDetailColumns = () => {
        let data = [
            {
                title: '姓名',
                dataIndex: 'patName',
                width: 100,
                align: "center",
            },
            {
                title: '登记号',
                dataIndex: 'patNO',
                width: 100,
                align: "center"
            },
            {
                title: '床号',
                dataIndex: 'bedNO',
                width: 100,
                align: "center"
            },
            {
                title: '药品名称',
                dataIndex: 'stockDesc',
                width: 200,
                align: "center"
            }, {
                title: '是否皮试',
                dataIndex: 'skinTest',
                width: 300,
                align: "center",
            },
            {
                title: '库存数量',
                dataIndex: 'stkQty',
                width: 300,
                align: "center",
            },
            {
                title: '用法',
                dataIndex: 'usageDesc',
                width: 300,
                align: "center",
            },
            {
                title: '频次',
                dataIndex: 'freqDesc',
                width: 300,
                align: "center",
            },
            {
                title: '疗程',
                dataIndex: 'durMas',
                width: 300,
                align: "center",
            },
            {
                title: '执行时间',
                dataIndex: 'execTime',
                width: 300,
                align: "center",
            },

            {
                title: '剂量',
                dataIndex: 'dose',
                width: 300,
                align: "center",
            },
            {
                title: '数量',
                dataIndex: 'sum',
                width: 200,
                align: "center"
            },
            {
                title: '单位描述',
                dataIndex: 'unitDesc',
                width: 100,
                align: "center"
            },
            {
                title: '剂型',
                dataIndex: 'formDesc',
                width: 200,
                align: "center"
            },
            {
                title: '规格',
                dataIndex: 'stockSpec',
                align: "center"
            },
            {
                title: '发药类别',
                dataIndex: 'dispCatID',
                width: 100,
                align: "center"
            },
        ]
        this.setState({ dispDetailColumns: data })
    }

    // 获取发药明细tabs栏表头数据
    getDispDetailTableData = (flag) => {
        let { pharmacy, startDate, endDate, wardSelectedRows, depDispensing, priorityCheckboxData, registrationRowData, drugName } = this.state;
        let wardData = JSON.parse(JSON.stringify(wardSelectedRows));
        let dispCatData = JSON.parse(JSON.stringify(this.state.dispCatData));
        let arr = [];
        let priority = [];
        for (var i = 0; i < dispCatData.length; i++) {
            if (dispCatData[i].checked) {
                arr.push(dispCatData[i].dispCatID)
            }
        }
        for (var i = 0; i < priorityCheckboxData.length; i++) {
            if (priorityCheckboxData[i].checked) {
                priority.push(priorityCheckboxData[i].id)
            }
        }
        for (var i = 0; i < wardData.length; i++) {
            wardData[i].dispCat = arr
        }
        let data = {
            params: [{
                startDate: startDate ? Moment(startDate).format('YYYY-MM-DD') : "", // 开始日期
                endDate: endDate ? Moment(endDate).format('YYYY-MM-DD') : "", // 截止日期
                recLocID: pharmacy, // 药房科室ID
                ward: flag === "registration" ? undefined : wardData, // 病区
                adm: flag === "registration" ? registrationRowData : undefined,
                priority, // 医嘱优先级
                locDispFlag: depDispensing, // 是否为科室发药
                stockDesc: drugName ? drugName : undefined
            }]
        }
        $http.post('urlS', this, {
            code: "02040024",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    for (var i = 0; i < res.rows.length; i++) {
                        res.rows[i].key = i;
                        res.rows[i].check = true;
                    }
                    this.setState({ dispDetailTableData: res.rows, dispDetailCheckbox: res.rows })
                } else {
                    this.setState({ dispDetailTableData: [] })
                }
            }
        })
    }

    filterDispensingData = () => {
        let { activeDispensingTab, summarizingCheckbox, dispDetailCheckbox } = this.state;
        let data = activeDispensingTab === '1' ? summarizingCheckbox : (activeDispensingTab === '2' ? dispDetailCheckbox : []);
        let obj = {};
        let ordDispen = [];
        let dispCatID = data[0].dispCatID;
        let obj2 = {};
        for (var i = 0; i < data.length; i++) {
            ordDispen = ordDispen.concat(data[i].ordDispen)
        }
        obj.wardID = data[0].wardID;
        obj2[dispCatID] = ordDispen;
        obj.dispCat = [];
        obj.dispCat.push(obj2);
        obj.ordDispenArr = ordDispen; // 拒绝发药时所需的ordDispen
        return obj;
    }

    // 住院发药
    handleHPDispensing = () => {
        let { pharmacy, activeTabPaneKey, activeDispensingTab, offsetDrug } = this.state;
        let arr = [];
        let obj = this.filterDispensingData();
        arr.push(obj)
        let data = {
            params: [{
                resFlag: offsetDrug,
                detail: [{
                    recLocID: pharmacy, // 药房科室ID
                    ward: arr, // 病区
                }],
                // ordDispen: obj.ordDispenArr
            }]
        }
        $http.post('urlS', this, {
            code: "02040027",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    if (res.str === "") {
                        message.success("发药成功");
                    } else {
                        const modal = Modal.error({
                            title: '欠费提示',
                            okText: '我知道了',
                            content: <div>
                                <div>{res.str + "因欠费导致无法发药。"}</div>
                            </div>
                        });
                    }
                    if (+res.conntFlag != 0) {
                        this.printAll(res.inDispIDArr);
                    }
                    if (activeTabPaneKey === '2') {
                        if (activeDispensingTab === '1') {
                            this.getSummarizingTableData("registration"); // 发要汇总
                        } else if (activeDispensingTab === '2') {
                            this.getDispDetailTableData("registration");
                        }
                    } else {
                        if (activeDispensingTab === '1') {
                            this.getSummarizingTableData(); // 发要汇总
                        } else if (activeDispensingTab === '2') {
                            this.getDispDetailTableData();
                        }
                    }
                }
            }
        })
    }

    printAll = (inDispIDArr) => {
        inDispIDArr.map((item, index) => {
            var inDispID = item;
            this.getPrintType(inDispID)
        })
    }
    /**获取打印类型
     */
    getPrintType = (rowId) => {
        const data = {
            params: [{ inDispID: rowId }]
        };
        $http.post('urlS', this, {
            code: "02040065",
            data: data,
            success: function (res) {
                // console.log(res)
                if (+res.errorCode === 0) {
                    let printType = res.result.prop
                    if (printType) {
                        if (printType.PrintSum === "1") {
                            this.printSummary(rowId)
                        }
                        if (printType.PrintDetail === "1") {
                            //this.printDetailed(rowId)
                        }
                    }
                }
            }
        })
    }
    /**打印发药汇总
     */
    printSummary = (rowId) => {
        const data = {
            params: [{ dispID: rowId }]
        };
        $http.post('urlS', this, {
            code: "02040060",
            data: data,
            success: function (res) {
                // console.log(res)
                if (+res.errorCode === 0) {
                    $loopPrint('', res.result);
                } else {
                    message.error(res.errorMessage);
                }
            }
        })
    }
    /**打印发药明细
     */
    printDetailed = (rowId) => {
        const data = {
            params: [{ dispID: rowId }]
        };
        $http.post('urlS', this, {
            code: "02040061",
            data: data,
            success: function (res) {
                // console.log(res)
                if (+res.errorCode === 0) {
                    $loopPrint('', res.result);
                } else {
                    message.error(res.errorMessage);
                }
            }
        })
    }

    // 登记号行操作
    handleregistrationOnRow = (record) => {
        return {
            // 单击行选中
            onClick: () => {
                if (this.state.registrationRowId === '') {
                    // 保存行数据以及ID
                    this.setState({ registrationRowId: record.admID, registrationRowData: record }, () => {
                        if (this.state.activeDispensingTab === '1') {
                            this.getSummarizingTableData("registration"); // 发要汇总
                        } else {
                            this.getDispDetailTableData("registration"); // 发药明细
                        }
                    })
                } else {
                    if (this.state.registrationRowId !== record.admID) {
                        this.setState({ registrationRowId: record.admID, registrationRowData: record }, () => {
                            if (this.state.activeDispensingTab === '1') {
                                this.getSummarizingTableData("registration"); // 发要汇总
                            } else {
                                this.getDispDetailTableData("registration"); // 发药明细
                            }
                        })
                    }
                }
            }
        }
    }

    handleregistrationRowClassName = (record) => {
        return record.admID === this.state.registrationRowId ? 'clickRowStyle' : '';
    }

    onRejectRef = ref => {
        this.rejectRef = ref;
    }

    // 拒绝发药
    handleRejectDispensing = () => {
        this.rejectRef.handleShowModal()
    }

    render() {
        let { pharmacy, startDate, endDate, selectData, offsetDrug, depDispensing, basicHeight, wardSelectedRowKeys, wardSelectedRows, activeTabPaneKey, drugName, reasonSelectData,
            wardID, wardSelectData, columns, tableData, patNo, registrationColumns, registrationTableData, activeDispensingTab, summarizingTableData, dispCatData,
            summarizingColumns, dispDetailColumns, dispDetailTableData, summarizingCheckbox, dispDetailCheckbox, priorityCheckboxData, detailWidthTotal, columnsCollect, modalColumns, listLength
        } = this.state;
        const wardRowSelection = {
            selectedRowKeys: wardSelectedRowKeys,
            selectedRows: wardSelectedRows,
            onChange: (selectedRowKeys, selectedRows) => {
                let rowId = "";
                if (selectedRowKeys.length !== 0) {
                    rowId = selectedRowKeys[selectedRowKeys.length - 1];
                }
                this.setState({ wardSelectedRowKeys: selectedRowKeys, wardSelectedRows: selectedRows, wardRowId: rowId })
            }
        };

        let summarizingParams = {
            data: summarizingTableData,
            columns: columnsCollect && columnsCollect.length > 0 ? columnsCollect : summarizingColumns,
            height: store.getState().tableHeight.y + 62 - basicHeight + 'px',
            width: columnsCollect && columnsCollect.length > 0 ? detailWidthTotal : 800,
            rowClassName: "redTable",
            // 选中数据
            onChange: (filterData, data) => {
                this.setState({ summarizingCheckbox: filterData, summarizingTableData: data });
            }
        }

        // 发要明细当中的组件所需参数
        let detailParams = {
            data: dispDetailTableData,
            columns: modalColumns && modalColumns.length > 0 ? modalColumns : dispDetailColumns,
            height: store.getState().tableHeight.y + 62 - basicHeight + 'px',
            width: modalColumns && modalColumns.length > 0 ? listLength : 800,
            // 选中数据
            onChange: (filterData, data) => {
                this.setState({ dispDetailCheckbox: filterData, dispDetailTableData: data })
            }
        }

        // 药房
        let pharmacyOption = selectData.loc && selectData.loc.map((item, index) => {
            return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        // 病区
        let wardAreaOption = wardSelectData && wardSelectData.map((item, index) => {
            return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        // 发药类别
        let dispTypeCheckbox = dispCatData && dispCatData.map((item, index) => {
            return (<Checkbox checked={item.checked} disabled={item.disabled} key={index} onChange={(e) => this.changeCheckbox(e, item)}>{item.dispCatDesc}</Checkbox>)
        })

        let priorityCheckbox = priorityCheckboxData && priorityCheckboxData.map((item, index) => {
            return (<Checkbox checked={item.checked} key={index} onChange={(e) => this.priorityCheckboxChange(e, item)}>{item.desc}</Checkbox>)
        })
        let param = {
            // 如果弹窗宽度修改了则要基于600做减法(比如变成了800则需要减去200)
            width: '600px',
            top: this.state.top,
            left: this.state.left,
            columns: this.modalColumns,
            data: this.state.modalData,
            isOnRow: true,
            TableClassName: 'tab-placeholder',
        };
        return (
            <div className="hospital-pharmacies">
                <Row id="dep-ward-dispensing" style={{ padding: '0 24px' }}>
                    <Col span={16}>
                        <div style={{ marginBottom: '8px' }}>
                            药房：<Select value={pharmacy} onChange={this.handlePharmacyOnChange} showSearch optionFilterProp="seatchprop" placeholder="请选择" style={{ width: '150px', margin: '8px 15px 0 0' }}>
                                {pharmacyOption}
                            </Select>
                            <DatePicker
                                value={startDate}
                                onChange={this.handleStartDate}
                                style={{ width: '150px', marginTop: '8px' }}
                                placeholder="开始日期"
                                allowClear={false}
                            />
                            <span style={{ display: 'inline-block', margin: '0 5px' }}>到</span>
                            <DatePicker
                                value={endDate}
                                onChange={this.handleEndDate}
                                style={{ width: '150px', marginRight: '15px' }}
                                placeholder="结束日期"
                                allowClear={false}
                            />
                            <Checkbox checked={offsetDrug} onChange={this.handleCheckbox}>冲减退药</Checkbox>
                            <Checkbox checked={depDispensing} onChange={this.handleDepartmentCheckbox} style={{ margin: '0 15px' }} >科室发药</Checkbox>
                            <Button style={{ marginTop: '8px' }} onClick={this.getTableData}>查询</Button>
                        </div>
                    </Col>
                    <Col span={8} style={{ textAlign: 'right' }}>
                        <Button
                            ghost
                            type="danger"
                            style={{ margin: '8px 15px 0 0', width: '100px' }}
                            onClick={this.handleRejectDispensing}
                            disabled={activeDispensingTab === '1' ? (summarizingCheckbox && summarizingCheckbox.length > 0 ? false : true) : (dispDetailCheckbox && dispDetailCheckbox.length > 0 ? false : true)}
                        >
                            拒绝发药
                        </Button>
                        <Button
                            type="primary"
                            style={{ marginTop: '8px', width: '100px' }}
                            onClick={this.handleHPDispensing}
                            disabled={activeDispensingTab === '1' ? (summarizingCheckbox && summarizingCheckbox.length > 0 ? false : true) : (dispDetailCheckbox && dispDetailCheckbox.length > 0 ? false : true)}
                        >
                            发药
                        </Button>
                    </Col>
                </Row>
                <div style={{ height: '6px', background: 'rgba(240, 242, 245, 1)', width: '100%' }}></div>
                <Row>
                    <Col span={6} className="card-container">
                        <Tabs activeKey={activeTabPaneKey} onChange={this.toggleTabPane} type="card">
                            <TabPane tab={depDispensing ? '科室列表' : '病区列表'} key="1">
                                <div style={{ padding: '12px', height: store.getState().tableHeight.y + 198 - basicHeight + 'px', overflow: 'auto' }}>
                                    <Row style={{ marginBottom: '12px' }}>
                                        <Col span={16}>
                                            <Select
                                                showSearch
                                                defaultActiveFirstOption={false}
                                                showArrow={false}
                                                filterOption={false}
                                                onSearch={this.handleWardSelectData}
                                                notFoundContent={null}
                                                placeholder={depDispensing ? '搜索科室' : '搜索病区'}
                                                allowClear
                                                style={{ width: '100%' }}
                                                value={wardID}
                                                onChange={this.handleWardOnChange}
                                            >
                                                {wardAreaOption}
                                            </Select>
                                        </Col>
                                        <Col span={8} style={{ textAlign: 'center' }}>
                                            <Button
                                                style={{ width: '116px' }}
                                                onClick={this.handleDispensingDetailData}
                                            // disabled={wardSelectedRows&&wardSelectedRows.length > 0 ? false : true}
                                            >
                                                查询发药明细
                                            </Button>
                                        </Col>
                                    </Row>
                                    <Table
                                        className="remove-td-default-bg"
                                        rowSelection={wardRowSelection}
                                        columns={columns}
                                        dataSource={tableData}
                                        bordered
                                        pagination={false}
                                        // scroll={{y: store.getState().tableHeight.y + 160 - 85 - basicHeight}}
                                        onRow={this.handleWardOnRow}
                                        rowClassName={this.handleWardRowClassName}
                                    // className="inpatient-area"
                                    />
                                </div>
                            </TabPane>
                            <TabPane tab="登记号" key="2">
                                <div style={{ padding: '12px', height: store.getState().tableHeight.y + 198 - basicHeight + 'px', overflow: 'auto' }}>
                                    <div style={{ marginBottom: '12px' }}>
                                        <Input
                                            style={{ width: '100%' }}
                                            value={patNo}
                                            onChange={this.handlePatNoOnChange}
                                            // onBlur={this.handleRegistrationInput}
                                            onPressEnter={this.getRegistrationTableData}
                                            placeholder={depDispensing ? "可以根据登记号、床位或姓名搜索(Enter)" : "可以根据登记号或姓名搜索(Enter)"}
                                        />
                                    </div>
                                    <Table
                                        columns={registrationColumns}
                                        dataSource={registrationTableData}
                                        bordered
                                        pagination={false}
                                        scroll={{ x: 380 }}
                                        onRow={this.handleregistrationOnRow}
                                        rowClassName={this.handleregistrationRowClassName}
                                    // className="inpatient-area"
                                    />
                                </div>
                            </TabPane>
                        </Tabs>
                    </Col>
                    <Col span={18}>
                        <div style={{ paddingLeft: '6px', position: 'relative' }}>
                            <Card
                                size="small"
                                title={<div className="card-title-left-icon"><div></div>{depDispensing ? '科室发药明细' : '病区发药明细'}</div>}
                            >
                                <div style={{ height: store.getState().tableHeight.y + 174 - basicHeight + 'px', overflow: 'auto' }}>
                                    <Row>
                                        <Col span={14}>
                                            {dispTypeCheckbox}
                                            <Divider type="vertical" />
                                            {priorityCheckbox}
                                        </Col>
                                        <Col id='stock-desc' span={10}>
                                            药品名称：<Input style={{ width: "200px" }} placeholder='回车检索药品相关信息' allowClear onPressEnter={this.stockDescOnPressEnter} value={drugName} onChange={this.handleDrugNameChange} />
                                        </Col>
                                    </Row>
                                    <Tabs activeKey={activeDispensingTab} onChange={this.toggleDispensingTabPane}>
                                        <TabPane tab="发药汇总" key="1">
                                            <div style={{ height: store.getState().tableHeight.y + 62 - basicHeight + 'px' }}>
                                                <ProtogenesisTable params={summarizingParams} />
                                            </div>
                                        </TabPane>
                                        <TabPane tab="发药明细" key="2">
                                            <div style={{ height: store.getState().tableHeight.y + 62 - basicHeight + 'px' }}>
                                                <ProtogenesisTable params={detailParams} />
                                            </div>
                                        </TabPane>
                                    </Tabs>
                                </div>
                            </Card>
                            <div style={{ width: '6px', background: 'rgba(240, 242, 245, 1)', position: 'absolute', top: 0, left: 0, height: '100%' }}></div>
                        </div>
                    </Col>
                </Row>
                <RejectDispensingCause onRef={this.onRejectRef} reasonSelectData={reasonSelectData} getOrdDispenData={this.filterDispensingData} handleQuery={this.handleDispensingDetailData} />
                <ColumnAuthoritysModel
                    clientWidth='800px'
                    compontName={this.state.parameterCode}
                    configType="C"
                    onRef={this.onColumnRef}
                    reloadData={() => {
                        if (this.state.parameterCode == 'HPDispensingCollect') {
                            this.getDetailTableColumns()
                        } else if (this.state.parameterCode == 'HPDispensingDetail') {
                            this.getDetailListTableColumns()
                        }
                    }
                    }
                />
                {/* <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName='DepartmentDrugInformationMaint'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.getDetailTableColumns1}
                    /> */}
                <PublicModalTable onClickRowPublic={this.onClickRowPublic} param={param} onRef={this.onRef} />
            </div>
        )
    }
}
